package com.longtop.framework.sys.user.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.LinkedMap;

import com.longtop.framework.base.BaseService;
import com.longtop.framework.common.CacheUtil;
import com.longtop.framework.common.Constant;
import com.longtop.framework.security.BaseCheckedException;
import com.longtop.framework.security.BaseUncheckedException;
import com.longtop.framework.security.MD5Util;
import com.longtop.framework.security.SessionObject;
import com.longtop.framework.sys.codeInfo.model.TSysCodeInfo;
import com.longtop.framework.sys.file.excel.ExcelBean;
import com.longtop.framework.sys.file.excel.ExcelExtractor;
import com.longtop.framework.sys.org.model.TSysOrg;
import com.longtop.framework.sys.role.model.TSysUserRole;
import com.longtop.framework.sys.user.model.TSysUser;
import com.longtop.framework.util.StringUtil;
import com.longtop.intelliweb.action.IActionContext;
import com.longtop.intelliweb.action.IInitContext;
import com.longtop.intelliweb.view.Text;

public class UserService extends BaseService {

	public static final String BEAN_ID = "userService";

	/**
	 * 保存、修改一起做！
	 * 
	 * @param changeMap
	 *            对象列表，有三个值，删除主键列表、更新bean的列表、新增bean的列表
	 * @param sessionObject
	 * @return 操作成功受影响的记录数，有三个值，插入成功的记录数、更新成功的记录数、删除成功的记录数
	 * @throws BaseCheckedException
	 */
	public Integer[] saveUser(Map changeMap, SessionObject sessionObject) throws BaseCheckedException {

		// 插入成功的记录数、更新成功的记录数、删除成功的记录数
		int insertCount = 0;
		int updateCount = 0;
		int deleteCount = 0;

		// 删除主键列表、更新bean的列表、新增bean的列表
		List insertBeanList = (ArrayList) changeMap.get(Constant.INSERT_BEAN_LIST);
		List updateBeanList = (ArrayList) changeMap.get(Constant.UPDATE_BEAN_LIST);
		String idList = (String) changeMap.get(Constant.ID_LIST);

		TSysUser user;
		Iterator iterator;

		// 批量插入记录
		if (insertBeanList.size() > 0) {
			iterator = insertBeanList.iterator();
			while (iterator.hasNext()) {
				user = (TSysUser) iterator.next();

				// 校验id是否重复。
				List list = this.queryAll("from TSysUser where userId='" + user.getUserId() + "'");
				if (list.size() > 0)
					throw new BaseCheckedException("", "保存失败,用户id【" + user.getUserId() + "】已经存在!");

				// 密码MD5加密：
				String MD5password = MD5Util.jiaMi(user.getPassword());
				user.setPassword(MD5password);
				super.save(user);

				// 保存初始员工对应角色表：
				TSysUserRole userRole = new TSysUserRole();
				userRole.setHomeUrl("/welcome.jsp");
				userRole.setRoleId(user.getRoleId());
				userRole.setUserId(user.getUserId());
				super.save(userRole);

				insertCount++;
			}
		}

		// 批量更新记录
		if (updateBeanList.size() > 0) {
			iterator = updateBeanList.iterator();
			while (iterator.hasNext()) {
				user = (TSysUser) iterator.next();
				// 取出用户原有的密码，验证密码是否有改变
				String oldPswd = this.queryForObjectByIbatis("sysUserSql.findUserPassword", user.getUserId()).toString();
				if (!user.getPassword().equals(oldPswd)) {// 不相等时加密。密码相同则不做加密，保持原密码
					user.setPassword(MD5Util.jiaMi(user.getPassword()));
				}
				super.update(user);

				// 更新员工对应角色表：
				List list = this.queryAll("from TSysUserRole where userId = '" + user.getUserId() + "' and roleId = '" + user.getRoleId() + "'");
				if (list != null && list.size() <= 0) {// 找不到原相关的角色则新插入
					TSysUserRole userRole = new TSysUserRole();
					userRole.setHomeUrl("/welcome.jsp");
					userRole.setRoleId(user.getRoleId());
					userRole.setUserId(user.getUserId());
					super.save(userRole);
				}

				updateCount++;
			}
		}

		// 批量删除记录
		if (idList.length() > 0) {
			String sql = "delete from TSysUser where userId in(" + idList + ")";
			deleteCount = super.batchUpdate(sql);
			// deleteAll删除该用户的 用户角色关系
			this.deleteAll(this.queryAll("from TSysUserRole where userId in(" + idList + ")"));
		}
		return new Integer[] { new Integer(insertCount), new Integer(updateCount), new Integer(deleteCount) };
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @throws BaseCheckedException
	 */
	public void deleteUser(String userId) throws BaseCheckedException {
		super.delete(TSysUser.class, userId);
	}

	/**
	 * 读取 用户org 信息 ,并根据 用户id 组织成一个 Map， 此方法供 系统启动时候的Listener调用。
	 * 
	 * @return 用户信息的Map
	 * @author 胡砥峰
	 */
	public Map<String, TSysUser> getUserMap() {
		Map userMap = new HashMap();
		List list = this.queryAll("from TSysUser where status='1'");
		TSysUser user;
		Iterator it = list.iterator();
		while (it.hasNext()) {
			user = (TSysUser) it.next();
			userMap.put(user.getUserId(), user);
		}

		return userMap;
	}

	/**
	 * 根据选择的用户机构查找MAX用户ID
	 * 
	 * @param userOrgId
	 *            根据传入的orgId截取前2位，再查找数据库最大值+1；
	 * @return
	 */
	public String getMaxUserId(String userOrgId) {
		String resultUserId = "";
		String strOrgId = userOrgId.substring(0, 2);// orgId截取前2位

		String hql = "select max(u.userId) from TSysUser u where u.isVirtual='0' and  u.userId like '" + strOrgId + "%'";
		List list = this.queryAll(hql);
		if (list == null || list.size() <= 0 || StringUtil.getString(list.get(0)).equals("")) {
			resultUserId = strOrgId + "0001";
		} else {
			resultUserId = StringUtil.getString(list.get(0));
			// 在原STR上加1后，左端补齐原有的0的个数
			resultUserId = StringUtil.plusOneLeftPad(resultUserId);
		}
		return resultUserId;
	}

	/**
	 * 导出用户列表详细
	 * 
	 * @param list
	 * @param context
	 * @throws Exception
	 */
	public void exportUser(List<Map<String, Object>> list, IActionContext context) throws Exception {
		if (list == null || list.size() <= 0) {
			throw new BaseUncheckedException("导出数据为空。");
		}

		// 合并单元格excel头部
		Map<String, Integer> groupColumn = new LinkedMap();
		String orgName = context.getElementText("Text_orgId");
		String orgId = context.getElementValue("Text_orgId");
		String groupTitle = orgName + "(" + orgId + ")";
		System.out.println(groupTitle);
		groupColumn.put(groupTitle + " —— 员工详细列表", 9);

		// 构建 excel头部：
		Map<String, Object> excelHeadMap = new LinkedMap();
		excelHeadMap.put("userId", "员工号");
		excelHeadMap.put("userName", "员工姓名");
		excelHeadMap.put("loginName", "OA用户名");
		excelHeadMap.put("orgId", "所属部门号");
		excelHeadMap.put("orgName", "所属部门名称");
		excelHeadMap.put("cardNo", "身份证号码");
		excelHeadMap.put("sex", "性别");
		excelHeadMap.put("duty", "职务");

		// 构建excel单元格值：
		List<Map<String, Object>> valueMapList = new ArrayList<Map<String, Object>>();
		Map<String, Object> valueMap;

		List<TSysCodeInfo> dutyList = CacheUtil.getCodeInfoListByCodeTypeId("USER_DUTY");

		for (Map<String, Object> map : list) {
			valueMap = new LinkedMap();

			// 从码表取职务名称：
			String duty = "";
			if (!StringUtil.isEmpty(map.get("duty"))) {
				for (TSysCodeInfo sysCodeInfo : dutyList) {
					if (sysCodeInfo.getValue().equals(map.get("duty"))) {
						duty = sysCodeInfo.getContent();
						break;
					}
				}
			}
			valueMap.put("userId", map.get("userId"));
			valueMap.put("userName", map.get("userName"));
			valueMap.put("loginName", map.get("loginName"));
			valueMap.put("orgId", map.get("orgId"));
			valueMap.put("orgName", map.get("orgName"));
			valueMap.put("cardNo", map.get("cardNo"));
			valueMap.put("sex", map.get("sex").toString().equals("1") ? "男" : "女");
			valueMap.put("duty", duty);

			valueMapList.add(valueMap);
		}
		ExcelBean excelBean = new ExcelBean("USER_LIST", "USER_LIST");
		excelBean.setExcelHeadMap(excelHeadMap);
		excelBean.setGroupColumn(groupColumn);

		ExcelExtractor excutor = new ExcelExtractor(excelBean);
		excutor.exportExcel(valueMapList, context);

	}

	/**
	 * 根据用户数据权限，设置默认机构值：权限控制
	 * 
	 * @param context
	 * @return 返回ORGID
	 */
	public String getOrgIdByAuth(IInitContext context) {
		SessionObject sessionObject = (SessionObject) context.getRequest().getSession().getAttribute(Constant.SESSION_OBJECT);
		String filter = sessionObject.getGrantFilterSql("T_SYS_ORG", "O", "ORG_ID", null);
		String orgId = "";
		if (filter.indexOf("like") != -1) {
			orgId = filter.substring(filter.lastIndexOf('%') - 5, filter.lastIndexOf('%'));
		} else if (filter.indexOf("=") != -1 && filter.indexOf("(") != -1) {
			orgId = filter.substring(filter.lastIndexOf("'") - 5, filter.lastIndexOf("'"));
		}

		// 设置页面Text_orgId 的默认值
		if (!StringUtil.isEmpty(orgId)) {
			Text textOrgId = (Text) context.getControl("Text_orgId");
			TSysOrg sysOrg = this.get(TSysOrg.class, orgId);
			String orgName = sysOrg.getOrgName();
			textOrgId.setValue(orgId, orgName);
		}
		return orgId;
	}

}